package org.finesys.chat.core.base.document.source;

import org.finesys.chat.core.base.document.Metadata;
import org.finesys.common.core.util.ValidationUtil;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;

public class ClassPathSource implements DocumentSource {

    private final URL url;
    private final ClassLoader classLoader;
    private final Metadata metadata = new Metadata();

    public ClassPathSource(URL url, ClassLoader classLoader) {
        this.url = ValidationUtil.ensureNotNull(url, "URL");
        this.classLoader = ValidationUtil.ensureNotNull(classLoader, "ClassLoader");
        String file = this.url.getFile();
        metadata.put("fileName", file.substring(file.lastIndexOf(47) + 1));
        metadata.put("url", this.url.toString());
    }

    public static ClassPathSource from(String classPath) {
        return from(classPath, Thread.currentThread().getContextClassLoader());
    }

    public static ClassPathSource from(String classPathResource, ClassLoader classLoader) {
        String resource = ValidationUtil.ensureNotNull(classPathResource, "classPathResource");
        ClassLoader cl = classLoader == null ? Thread.currentThread().getContextClassLoader() : classLoader;
        URL url = ValidationUtil.ensureNotNull(cl.getResource(resource), String.format("Resource [%s] not found in classpath", resource));
        return new ClassPathSource(url, cl);
    }

    public URL url() {
        return url;
    }

    public ClassLoader classLoader() {
        return classLoader;
    }

    public boolean isInsideArchive() {
        return "jar".equalsIgnoreCase(this.url.getProtocol());
    }

    @Override
    public InputStream inputStream() throws IOException {
        return url.openStream();
    }

    @Override
    public Metadata metadata() {
        return this.metadata;
    }
}
